package cn.bisoft.java.util.os;

import java.net.URL;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;

/**
 * 打印机辅助类.
 * @author tl
 * @version 1.0, 2011-5-17
 */
public class PrinterUtil
{

	/**
	 * 获取本地所有可用的打印机.
	 * @return 打印机
	 */
	public static PrintService[] lookupPrinter()
	{
		return PrintServiceLookup.lookupPrintServices(null, null);
	}

	/**
	 * 获取本地默认的打印机.
	 * @return 打印机
	 */
	public static PrintService lookupDefaultPrinter()
	{
		return PrintServiceLookup.lookupDefaultPrintService();
	}

	/**
	 * 打印.
	 * @param ps 打印服务
	 * @param doc 文档
	 * @param attrs 打印机属性
	 */
	public static void print(PrintService ps, Doc doc, PrintRequestAttributeSet attrs)
	{
		if (null == ps)
		{
			System.err.println("没有找到可用的打印机");
		}
		else
		{
			DocPrintJob job = ps.createPrintJob();

			try
			{
				job.print(doc, attrs);
			}
			catch (PrintException e)
			{
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取文档.
	 * @param url 文档地址
	 * @param flavor 文档类型
	 * @return 文档
	 */
	public static SimpleDoc getSimpleDoc(URL url, DocFlavor flavor)
	{
		SimpleDoc doc = new SimpleDoc(url, flavor, null);

		return doc;
	}

	/**
	 * 示例
	 */
	public static void example()
	{
		PrintService printService = PrinterUtil.lookupDefaultPrinter();

		try
		{
			URL url = new URL("http://www.apress.com/ApressCorporate/supplement/1/421/bcm.gif ");

			DocFlavor flavor = DocFlavor.URL.GIF;

			Doc doc = PrinterUtil.getSimpleDoc(url, flavor);

			PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();

			// 复制2份
			attrs.add(new Copies(2));

			PrinterUtil.print(printService, doc, attrs);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

}
